<template>
  <div>
    <H2>规则表</H2>
    <!-- <ccnRuleTable /> -->

    <FactorPanel
      :type="ConditionType.Col"
      title="列因子"
      group="item"
      :items="colConditions"
      @itemChange="
        ({ value }) => {
          colConditions = value
        }
      "
      @deleteButtonClick="
        ({ value }) => {
          colConditions = value
        }
      "
    />
    <FactorPanel
      :type="ConditionType.Row"
      title="行因子"
      group="item"
      :items="rowConditions"
      @itemChange="
        ({ value }) => {
          rowConditions = value
        }
      "
      @addButtonClick="add"
      @editButtonClick="edit"
      @deleteButtonClick="
        ({ value }) => {
          rowConditions = value
        }
      "
    />
    <br />

    <FCRuleTable
      :table="myTable"
      :colConditions="colConditions"
      :rowConditions="rowConditions"
      :results="results"
      :colResults="colResults"
      :cellResults="[]"
      :initDatas="initDatas"
      :mergedColumns="mergedColumns"
    />

    <a-drawer
      title="规则表"
      :visible="visible"
      @close="onClose"
      width="800"
      :maskClosable="false"
      :closable="true"
    >
      <a-row :gutter="[16, 8]">
        <a-form :form="form">
          <a-col :span="12">
            <a-form-item
              :label-col="{ span: 5 }"
              :wrapper-col="{ span: 19 }"
              label="因子代码"
            >
              <a-input v-decorator="['code', { rules: [{ required: true, message: '请输入代码' }] }]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="因子名称"
              :label-col="{ span: 5 }"
              :wrapper-col="{ span: 19 }"
            >
              <a-input v-decorator="['title', { rules: [{ required: true, message: '请输入名称' }] }]" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item
              :label-col="{ span: 3 }"
              :wrapper-col="{ span: 21 }"
              label="因子描述"
            >
              <a-input v-decorator="['description']" />
            </a-form-item>
          </a-col>
        </a-form>
      </a-row>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button
          :style="{ marginRight: '8px' }"
          @click="onClose"
          >Cancel</a-button
        >
        <a-button
          type="primary"
          @click="onSubmit"
          >Submit</a-button
        >
      </div>
    </a-drawer>

    <a-space style="margin-top: 10px">
      <button @click="doUpdateTable">update table</button>
      <button @click="doTest">test it</button>
      <button @click="filterFn">过滤变更的数据</button>
      <button @click="recoverData">还原数据</button>
      <button @click="editTable">表格编辑</button>
      <button @click="editTableCompelete">表格编辑完成</button>
      <button @click="addRule">添加rule</button>
      <button @click="getRules">获取表格rules</button>
    </a-space>
  </div>
</template>

<script>
// import FCRuleTableInstance from '@/pages/rule-table-test/fc-rule-table/instance/FCRuleTableInstance'
// import ccnRuleTable from './fc-rule-table/ccnRuleTable/index.vue'
// import RuleTable from './fc-rule-table/ccnRuleTable/RuleTableCompont.vue'
import FCRuleTable from './fc-rule-table/FCRuleTable.vue'
// import Feature from '../dashboard/Feature'
import FactorPanel, { ConditionType } from './fc-rule-table/FactorPanel.vue'
import { colConditions, rowConditions, results, initData, colResults, mergedColumns } from './fc-rule-table/data'
export default {
  name: 'ruleTableTest',
  data() {
    // 规则表实例
    //
    // console.log('[index.vue] - data()')


    // 预期这句每次热更新都会执行
    const myTable = FCRuleTable.createTable()

    return {
      form: this.$form.createForm(this),
      visible: false,
      ConditionType,
      myTable,
      colConditions,
      rowConditions,
      // 规则表实例
      initDatas: initData,
      mergedColumns,
      results,
      colResults,
      type: '',
      selectedItems: {
        rowConditions,
        colConditions,
      },
    }
  },
  components: { FCRuleTable, FactorPanel },
  props: {},
  created() {
    // console.log('[index.vue] - created()')
    // this.selectedItems = []
  },
  mounted() {
    // const key = this.myTable.findRule({ condition: {  P04: '[0, 0.54)' } })
    // this.myTable.highlightValue(key.rowKey, 'P04')
    // const keys = this.myTable.findRule({ condition: { P02: '11', P03: 'a2', P04: '[0.54, 0.58)' } })
    // this.myTable.highlightValue(keys.rowKey, { P01: 1, P02: '22', P03: 'a2' })
  },
  methods: {
    // 跟新因子
    onFeatureUpdate: function (param) {
      param.name = ''
      console.log('因子组合发生变化:', param)
      const { colFeature, rowFeature } = param
      this.colConditions = colFeature
      this.rowConditions = rowFeature
    },
    addFeatures(value) {
      this.addFeature(value)
    },

    onClose() {
      this.visible = false
    },

    async onSubmit() {
      try {
        const res = await this.form.validateFields()
        console.log('type', this.type)
        if (this.type === ConditionType.Row) {
          this.rowConditions.push(res)
        } else if (this.type === ConditionType.Col) {
          this.colConditions.push(res)
        }
        this.visible = false
      } catch (error) {
        console.log('error', error)
      }
    },

    add({ type }) {
      this.type = type

      this.visible = true
      console.log('add', type)
    },

    edit({ type, value }) {
      this.type = type
      this.form.setFieldsValue(value)
      this.visible = true
      console.log('edit', type, value)
    },

    addFeature: function (value) {
      this.addFeatureVisible = true
      this.getAllFeatures()
      this.type = value
      if (Object.keys(this.param).length === 0) return
      console.log('proar', this.type, this.param)
      if (value === 'row') {
        this.selectedRowKeys = Array.from(new Set([...this.param.rowFeature.map((item) => item.id), ...this.param.colFeature.map((item) => item.id)]))
        console.log('====', this.selectedRowKeys)
      } else {
        this.selectedRowKeys = Array.from(new Set([...this.param.colFeature.map((item) => item.id), ...this.param.rowFeature.map((item) => item.id)]))
        console.log('====', this.selectedRowKeys)
      }
    },

    recoverData() {
      // this.myTable.highlightHeader({ P01: 1, P02: '11' })
      // this.myTable.mergeHeader({ start: { P01: 1, P02: '11', P03: 'a1' }, length: 2 })
      this.myTable.recoverData()
    },
    filterFn() {
      this.myTable.getHighlightData()
    },
    editTable() {
      this.myTable.isActive = true
    },
    editTableCompelete() {
      this.myTable.isActive = false
    },
    getRules() {
      // this.myTable.getAllRules()
      console.log(this.myTable.rules, 'rules')
      console.log(this.myTable.rowConditions, 'rowConditions')
      console.log(this.myTable.colConditions, 'colConditions')
      //  this.myTable.highlightValue('t:1-row:1','P04')
    },
    addRule() {
      this.myTable.addRule({ P01: 1, P02: '11', P03: 'a1', P04: '[0.67, 0.88)', R01: 0.85 })
    },
    doIt() {
      // console.log('>> table:', this.myTable.key)

      this.rowConditions = [
        {
          code: 'P02',
          title: '三责保额',
          options: [
            { value: '11', label: '三责保额 200 万及以上' },
            { value: '22', label: '三责保额 200 万以下' },
          ],
        },
        {
          code: 'P01',
          title: '车损情况',
          options: [
            { value: 1, label: '有车损' },
            { value: 0, label: '无车损' },
          ],
        },
        {
          code: 'P03',
          title: '续保类型',
          options: [
            { value: 'a1', label: '续续 0-1' },
            { value: 'a2', label: '续续 2-3' },
          ],
        },
      ]
    },
    doUpdateTable() {
      console.log('>>>>>>')
      this.colConditions = [
        {
          code: 'P05',
          title: '性别',
          options: [
            { value: '0', label: '女' },
            { value: '1', label: '男' },
          ],
        },
        { code: 'P04', title: '交商含 NCD 标费预赔' },

        //   // { code: 'P05', title: '交商含 NCD 标费预赔5' },
      ]
      // this.rowConditions = [
      //   {
      //     code: 'P01',
      //     title: '⻋损情况',
      //     options: [
      //       { value: 1, label: '有⻋损' },
      //       { value: 0, label: '⽆⻋损' },
      //     ],
      //   },
      //   {
      //     code: 'P02',
      //     title: '三责保额',
      //     options: [
      //       { value: '11', label: '三责保额 300 万及以上' },
      //       { value: '22', label: '三责保额 200万 - 300万' },
      //       { value: '33', label: '三责保额 200 万以下' },
      //     ],
      //   },
      //   {
      //     code: 'P03',
      //     title: '续保类型',
      //     options: [
      //       { value: 'a1', label: '新续' },
      //       { value: 'a2', label: '转续' },
      //       // { value: 'a3', label: '续续 2-3' },
      //       // { value: 'a4', label: '续续 4-5' },
      //       // { value: 'a5', label: '续续 6+' },
      //     ],
      //   },
      //   //
      // ]
      // this.colResults = [
      //   // { code: 'R02', title: '费率-2', dataType: 'number', linkProps: { openType: 'modal', label: '点击修改' } },
      //   { code: 'R03', title: '费率 333', dataType: 'number', linkProps: { openType: 'drawer' } },
      // ]

      this.myTable.doUpdateTable()
    },
    doTest() {
      console.log('>>> dataSource:', JSON.stringify(this.myTable.buildTableDataSource()))

      // console.log('now do test')
      // const factor = this.myTable.getCellFactorWithDataIndex('P04')
      // console.log('factor is:', factor)

      // const dataindexList = ['P04', '1-11-a1', '1-11-a2', '1-22-a1', '1-22-a2', '0-11-a1', '0-11-a2', '0-22-a1', '0-22-a2', 'R02', 'R03']
      // dataindexList.forEach((dataIndex) => {
      //   const factor = this.myTable.getCellFactorWithDataIndex(dataIndex)
      //   console.log('dataIndex:', dataIndex, 'factor code:', factor.code)
      // })
    },
  },
}

/////////
function findSubArrays(arr1, arr2) {
  // 初始化结果数组
  let results = []

  // 遍历 arr1 中的每个可能的起始点
  for (let i = 0; i < arr1.length; i++) {
    // 遍历 arr2 中的每个子数组
    for (let j = 0; j < arr2.length; j++) {
      // 获取 arr2 中的子数组的起始元素和长度
      let startElement = arr2[j][0]
      let length = arr2[j].length

      // 检查 arr1 中从索引 i 开始的子数组是否与 arr2 中的子数组相匹配
      if (arr1.slice(i, i + length).every((element, index) => element === startElement + index)) {
        // 如果匹配，添加结果
        results.push({ start: i, length })
        break // 跳出内层循环，因为 arr1 的子数组不能同时匹配 arr2 中的多个子数组
      }
    }
  }

  return results
}

// 使用示例
let arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let arr2 = [
  [1, 2],
  [5, 6, 7],
  [9, 10],
]

// console.log('>>>>>>>', findSubArrays(arr1, arr2))
// 期望输出：[{ start: 0, length: 2 }, { start: 4, length: 3 }, { start: 8, length: 2 }]

////

function buildTree(factors, depth = 0, valuePath = []) {
  const result = []

  // 如果已经达到因子数组的末尾，返回一个空数组
  if (depth === factors.length) {
    return []
  }

  // 获取当前深度的因子数组
  const currentFactor = factors[depth]

  // 递归地为当前因子的每个值构建子树
  for (let i = 0; i < currentFactor.length; i++) {
    const childValuePath = [...valuePath, currentFactor[i]]
    const children = buildTree(factors, depth + 1, childValuePath)

    const dataIndex = children.length > 0 ? undefined : childValuePath.join('-')
    // const valuePath = children.length > 0 ? childValuePath : undefined

    // 创建当前节点，并附加子树
    result.push({
      title: currentFactor[i],
      dataIndex,
      valuePath: children.length > 0 ? undefined : childValuePath,
      children: children.length > 0 ? children : undefined,
    })
  }

  return result
}

// 使用示例
let factors = [
  ['a1', 'a2'], // 因子 a
  ['b1', 'b2', 'b3'], // 因子 b
  ['c1', 'c2', 'c3'], // 因子 c
]

const tree = buildTree(factors)
// console.log('>>>>> output tree is:', JSON.stringify(tree))
</script>

<style></style>
